package com.yjt.admin.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjt.admin.system.dao.PostMapper;
import com.yjt.admin.system.entity.EmpPost;
import com.yjt.admin.system.entity.Post;
import com.yjt.admin.system.form.PostForm;
import com.yjt.admin.system.param.PostParam;
import com.yjt.admin.system.service.EmpPostService;
import com.yjt.admin.system.service.PostService;
import com.yjt.admin.system.vo.PostVO;
import com.yjt.common.utils.ComUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 岗位表 服务实现类
 * </p>
 *
 * @author zzp
 * @since 2021-10-09
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Resource
    private PostMapper postMapping;

    @Autowired
    private EmpPostService empPostService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPost(PostForm postForm) {
        Post post = new Post();
        BeanUtils.copyProperties(postForm, post);
        //增加岗位信息
        this.save(post);
        //增加岗位与人员关联信息
        List<String> empIdList = postForm.getEmpIdList();
        if (ComUtil.isNotNullList(empIdList)) {
            empPostService.addEmpPost(post.getPostId(), post.getPostType(), empIdList);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePost(PostForm postForm) {
        Post post = new Post();
        BeanUtils.copyProperties(postForm, post);
        this.updateById(post);
        //增加岗位与人员关联信息
        List<String> empIdList = postForm.getEmpIdList();
        if (ComUtil.isNotNullList(empIdList)) {
            //删除员工与岗位关联的信息
            empPostService.remove(Wrappers.<EmpPost>lambdaQuery().eq(EmpPost::getPostId, postForm.getPostId()));
            //保存数据
            empPostService.addEmpPost(post.getPostId(), post.getPostType(), empIdList);
        }
    }

    @Override
    public IPage<PostVO> getPagePost(PostParam postParam) {
        return postMapping.findPagePost(postParam.toPage(), postParam);
    }

    @Override
    public PostVO getOnePost(String postId) {
        PostVO postVO = postMapping.findOnePost(postId);
        if (ComUtil.isNotNullStr(postVO.getEmplyIds())) {
            postVO.setEmplyIdList(Arrays.asList(postVO.getEmplyIds().split(",")));
        }
        if (ComUtil.isNotNullStr(postVO.getEmplyNames())) {
            postVO.setEmplyNameList(Arrays.asList(postVO.getEmplyNames().split(",")));
        }
        return postVO;
    }


}
